<template>
  <div>
    <!--引用表格-->

    <div class="treeBox">
      今日出单: <span class="red">{{ userData.orderCount }}</span> , 利润: <span class="red">{{ userData.profit }}</span>

      <a-button color="success" style="margin-left: 20px" @click="count" :loading="isloading">
        <template #icon><RedoOutlined /></template>刷新</a-button
      >
    </div>

    <BasicTable @register="registerTable">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!-- <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 创建订单</a-button> -->
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls(true)"> 导出</a-button>
      </template>
      <template #Index="{ index }">
        {{ index + 1 }}
      </template>
      <template #Foundation="{ record }">
        <div style="text-align: left">
          <div class="blue"> {{ record.title }}</div>
          <div>商品ID:{{ record.itemId }}</div>
          <div>订单状态:{{ record.orderStatus_dictText }}</div>
        </div>
      </template>
      <template #Detail="{ record }">
        <div style="text-align: left">
          <div
            >订单编号:<span class="blue">{{ record.orderNo }}</span></div
          >
          <div>创建时间:{{ record.orderTime }}</div>
          <div>发货时间:{{ record.consignTime }}</div>
        </div>
      </template>
      <template #Number="{ record }">
        <div style="text-align: left">
          <div
            >商品单价:<span class="">{{ record.price }}</span></div
          >
          <div>购买数量:{{ record.quantity }}</div>
          <div>实付金额:{{ record.payAmount }}</div>
        </div>
      </template>
      <template #Remake="{ record }">
        <div style="text-align: left">
          <div
            >卡券:<span class="">{{ record.cardIds }}</span></div
          >
          <div
            >备注:<span class="">{{ record.remark }}</span></div
          >
        </div>
      </template>
      <template #isShow="{ record }">
        <Image v-if="true" :src="record.images" :width="100" :height="100" />
        <div style="color: blue">{{ record.code }}</div>
      </template>

      <!--操作栏-->
      <template #action="{ record }">
        <TableAction
          :actions="getTableAction(record)"
          style="{ width: 400px;
          display: flex;
          flex-direction: column;}"
        />
      </template>

      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }"> </template>
    </BasicTable>
    <!-- 表单区域 -->
    <GoodfishOrderModal @register="registerModal" @success="handleSuccess"></GoodfishOrderModal>
    <GoodfishOrderModal2 @register="registerModal2" @success="reload"></GoodfishOrderModal2>
    <GoodfishOrderSendModal @register="registerSendModal" @success="reload" />
  </div>
</template>

<script lang="ts" name="card-goodfishOrder" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useModal } from '/@/components/Modal';
  import GoodfishOrderModal from './components/GoodfishOrderModal.vue';
  import GoodfishOrderModal2 from './components/GoodfishOrderModal2.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Image } from 'ant-design-vue';
  import { columns, searchFormSchema, superQuerySchema } from './GoodfishOrder.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportPageUrl, countList } from './GoodfishOrder.api';
  import GoodfishOrderSendModal from './components/GoodfishOrderSendModal.vue';
  import { useRouter } from 'vue-router';
  const router = useRouter();
  const { createMessage } = useMessage();
  const queryParam = reactive<any>({});
  const isloading = ref(false);
  //注册model
  const [registerSendModal, { openModal: openGoodfishOrderSendModal }] = useModal();
  const [registerModal2, { openModal: openGoodfishOrderModal2 }] = useModal();
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '咸鱼订单',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [['createTime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        count(params);
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '咸鱼订单',
      url: getExportPageUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const userData = reactive<any>({
    orderCount: '',
    profit: '',
  });
  async function count(params) {
    isloading.value = true;
    // let params = {};
    console.log('params', params);
    await countList(params, handleSuccesss);
  }

  function handleSuccesss(res) {
    Object.assign(userData, res);
    isloading.value = false;
  }
  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal: openGoodfishOrderSendModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  // 一键激活
  function handleJiHuo(record: Recordable) {
    openModal: openGoodfishOrderModal2(true, {
      record,
      isUpdate: true,
      showFooter: true,
      orderNo: record.orderNo,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: false,
    });
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  // 复制咸鱼订单号
  function copyOrderId(record) {
    try {
      const str = `您好，感谢光临小店！以下是您的发货内容：

券码类型：【美团券】
券码：${record.cardCodes}
二维码图片：https://fyyh.appldkj.com/#/?p=${record.orderNo}

使用说明如下：
——直接点击链接，结账或进店扫码出示二维码即可
——本券是美团券，需要店家使用美团平台核销。（一个二维码仅扫一次）

温馨提示：核销成功后请及时确认收货哦～ 祝您用餐愉快！`;
      if (str == '') {
        createMessage.error('复制失败,未选中数据');
        return;
      }
      if (navigator.clipboard) {
        navigator.clipboard.writeText(str);
        createMessage.success('复制成功');
      } else {
        const textarea = document.createElement('textarea');
        textarea.value = str;
        textarea.style.position = 'fixed';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        createMessage.success('复制成功');
      }
    } catch (error) {
      console.log(error);
      createMessage.error('复制失败');
    }
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    console.log('刷新');

    (selectedRowKeys.value = []) && reload();
  }
  function goDaiFu(record) {
    const currentUrl = window.location.href;
    let newUrl = currentUrl.replace('goodfishOrderList', `substituteList?id=${record.orderNo}`);
    console.log('newUrl', newUrl);
    window.open(newUrl, '_blank');
    // router.push({ path: '/card/substituteList', query: { id: record.orderNo } });
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '代付',
        onClick: goDaiFu.bind(null, record),
      },
      {
        label: '使用卡券',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '一键激活',
        onClick: handleJiHuo.bind(null, record),
      },
      {
        label: '复制发货链接',
        onClick: copyOrderId.bind(null, record),
        ifShow: (_action) => {
          return record.cardIds ? true : false;
        },
      },
    ];
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '使用卡券',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '一键激活',
        onClick: handleEdit.bind(null, record),
      },
      // {
      //   label: '代付',
      //   onClick: handleDetail.bind(null, record),
      // },
    ];
  }
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
  .treeBox {
    margin: 10px;
    background: #fff;
    padding: 20px;
    box-sizing: border-box;
    .red {
      color: red;
    }
  }
  .blue {
    color: rgb(13, 174, 255);
  }
</style>
